package com.jt.tenant.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jt.tenant.R;
import com.jt.tenant.app.JTApplication;
import com.jt.tenant.conn.GetLoginAdmin;
import com.jt.tenant.conn.GetRegisterUser;
import com.jt.tenant.conn.GetVerificationCode;
import com.jt.tenant.widget.Tools;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilToast;

import java.util.HashMap;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;

/**
 * Created by Administrator on 2016/3/1.
 */
public class Register1Activity extends JTActivity implements View.OnClickListener {

    private TextView tv_register_1,tv_register_2,tv_register_3;

    private EditText et_admin, et_pwd;

    private TextView tv_register_code;//获取验证码

    private TextView go_next;//下一步

    private TextView title_name;

    private String admin, pwd;

    private SharedPreferences.Editor editor;

    private SharedPreferences preferences;

    private int login_type;//模式，0：注册，1:微信登录创建账号 ，2：QQ登录创建账号,3：重置密码，

    private String account;

    private String true_account;

    private String identifying_code;//验证码

    private String account_flag;//账号状态,0:已激活，1：未激活

    private GetRegisterUser getRegisterUser = new GetRegisterUser(new AsyCallBack<GetRegisterUser.Info>() {

        @Override
        public void onSuccess(String toast, int type, GetRegisterUser.Info info) throws Exception {

            Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();

            JTApplication.jtPreferences.savePhone(admin);

            JTApplication.jtPreferences.saveUserId(info.userId);

            JTApplication.jtPreferences.saveHaveUid(true);

            JTApplication.jtPreferences.saveObdId(info.obdId);

            //saveToken
            JTApplication.jtPreferences.saveToken(info.token);

            getLoginAdmin.phone = admin;

            getLoginAdmin.type = "3";

            getLoginAdmin.execute(context);
        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
        }

    });

    private GetLoginAdmin getLoginAdmin = new GetLoginAdmin(new AsyCallBack<GetLoginAdmin.Info>() {

        @Override
        public void onSuccess(String toast, int type, GetLoginAdmin.Info info) throws Exception {

            if (info.msg.equals("000")) {

                if (!info.user_obdId.equals("") && !info.user_obdId.equals("null")) {

                    JPushInterface.setAliasAndTags(context, info.user_phone, JTApplication.tag, new TagAliasCallback() {

                        @Override

                        public void gotResult(int i, String s, Set<String> set) {

                            Log.e("JPush开启", "Jpush status: " + i);//状态

                        }
                    });

                }

                //无论什么情况都保存账号
                editor.putString("LoginUser", admin).commit();

                editor.putString("LoginPwd", "").commit();

                editor.putString("AutoLogin", "yes").commit();

                //存储数据
                JTApplication.jtPreferences.saveUserId(info.userId);

                JTApplication.jtPreferences.saveHaveUid(true);

                //saveObdId

                JTApplication.jtPreferences.saveObdId(info.user_obdId);

                if (!info.user_obdId.equals("") && !info.user_obdId.equals("null")) {

                    JTApplication.jtPreferences.saveHaveObdid(true);

                } else {

                    JTApplication.jtPreferences.saveHaveObdid(false);

                }
//                    //saveToken
                JTApplication.jtPreferences.saveToken(info.session_token);

                Log.e("TAG", "token=" + info.session_token + ",obdid=" + JTApplication.jtPreferences.readOdbID());
                //savePhone
                JTApplication.jtPreferences.savePhone(info.user_phone);
                //nickname
                JTApplication.jtPreferences.saveNickName(info.user_nickname);
                //头像
                JTApplication.jtPreferences.saveHeadPath(info.user_headpic);
                //车牌号
                JTApplication.jtPreferences.savePlateNum(info.car_plateNum);
                //车架号
                JTApplication.jtPreferences.saveVincode(info.car_vincode);
                //车辆id
                JTApplication.jtPreferences.saveCarId(info.car_id);

                //城市编号
                JTApplication.jtPreferences.saveCityCode(info.city_code);

                //机动车号
                JTApplication.jtPreferences.saveEngineCode(info.engine_code);

                //性别
                JTApplication.jtPreferences.saveSex(info.user_sex);

                //车id
                JTApplication.jtPreferences.saveCarId(info.carId);

                //车的归属类型
                JTApplication.jtPreferences.saveCarType(info.carType);

                //车型id
                JTApplication.jtPreferences.saveCategoryId(info.categoryId);

                //城市
                JTApplication.jtPreferences.saveCity(info.city);

                //购买时间
                JTApplication.jtPreferences.saveRemark(info.remark);

                //账号状态
                JTApplication.jtPreferences.saveAccountState(info.account_state);

                JTApplication.jtPreferences.saveBSX(info.bsx);

                JTApplication.jtPreferences.savePP(info.pp);

                JTApplication.jtPreferences.savePL(info.pl);

                JTApplication.jtPreferences.saveNK(info.nk);

                JTApplication.jtPreferences.saveCX(info.cx);

                //传送成功 存储图片路径
                JTApplication.jtPreferences.saveHeadPath(info.user_headpic);

                //存储 紧急账号(没用！！)
//                            JTApplication.jtPreferences.savePhone2(phone);
                //存储 昵称
                JTApplication.jtPreferences.saveNickName(info.user_nickname);

                //存储 WIFI状态
                JTApplication.jtPreferences.saveWIFI(info.wifi);

                //存储 GPS隐私管理
                if (info.gpsType.equals("0")) {

                    JTApplication.jtPreferences.savePrivacy(false);

                } else {

                    JTApplication.jtPreferences.savePrivacy(true);

                }


                //存储 WIFI密码
                JTApplication.jtPreferences.saveWIFIPWD(info.wifipwd);
                //存储 积分
//                    JTApplication.jtPreferences.saveUserIntegral(info.user_integralCount,"1");

                //存储保险状态
                JTApplication.jtPreferences.saveInsFlag(info.baoxianFlag);

                //存储驾驶证号
                JTApplication.jtPreferences.saveDriverNum(info.driverNum);

                //存储有效起始日期
                JTApplication.jtPreferences.saveDriverEffectiveDate(info.driverEffectiveDate);
                //存储有效期
                JTApplication.jtPreferences.saveDriverEffectiveYear(info.driverEffectiveYear);
                //性别
                if (info.user_sex.equals("1")) {

                    JTApplication.jtPreferences.saveSex("男");

                } else if (info.user_sex.equals("2")) {

                    JTApplication.jtPreferences.saveSex("女");

                }

                startActivity(new Intent(context, MainActivity.class));

                JTApplication.jtPreferences.saveShockNum(Integer.parseInt(Tools.F_num(info.tCollisionRemindValue)));

                JTApplication.jtPreferences.saveShockBool(Integer.parseInt(Tools.F_num(info.tCollisionRemindIsOpen)));

                for (int i = 0; i < info.personSet.size(); i++) {

                    if (info.personSet.get(i).equals("0")) {

                        JTApplication.jtPreferences.saveMessage(true, String.valueOf(i + 1));

                    } else {

                        JTApplication.jtPreferences.saveMessage(false, String.valueOf(i + 1));

                    }


                }


                Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show();

                finish();

            } else {

                Toast.makeText(context, info.msg, Toast.LENGTH_SHORT).show();

            }

        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            UtilToast.show(context, "连接超时");

        }

    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_register1);

        login_type = getIntent().getIntExtra("type",0);

        account = getIntent().getStringExtra("account");

        init_view();

    }

    private void init_view() {

        title_name = (TextView)findViewById(R.id.tv_title_name);

        tv_register_1 = (TextView)findViewById(R.id.tv_register_1);

        tv_register_2 = (TextView)findViewById(R.id.tv_register_2);

        tv_register_3 = (TextView)findViewById(R.id.tv_register_3);

        if(login_type == 3){

            tv_register_2.setText("重置密码");

            tv_register_3.setText("完成");

        }else if(login_type == 1 || login_type == 2){

            tv_register_1.setText("绑定手机号");

            tv_register_2.setText("设置密码");

            tv_register_3.setText("完成");

        }

        preferences = getSharedPreferences("tenant", MODE_PRIVATE);

        editor = preferences.edit();

        et_admin = (EditText) findViewById(R.id.et_admin);

        et_admin.clearFocus();

        et_pwd = (EditText) findViewById(R.id.et_pwd);

        (tv_register_code = (TextView)findViewById(R.id.tv_register_code)).setOnClickListener(this);

        (go_next = (TextView) findViewById(R.id.go_next)).setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.go_next:

                admin = et_admin.getText().toString().trim();

                pwd = et_pwd.getText().toString().trim();

                if (admin.equals("")) {

                    Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();

                } else if(!true_account.equals(admin)){

                    Toast.makeText(this, "手机号与验证码不符", Toast.LENGTH_SHORT).show();

                }else if (pwd.equals("")||!pwd.equals(identifying_code)||pwd.length()<4) {

                    Toast.makeText(this, "请正确输入验证码", Toast.LENGTH_SHORT).show();

                }else if (!Tools.isMobile(admin)) {

                    Toast.makeText(this, "手机号格式错误", Toast.LENGTH_SHORT).show();

                } else {

                    if(account_flag.equals("0") && (login_type == 1 || login_type == 2)){

                        register_net();

                    }else {

                        startActivity(new Intent(this, Register2Activity.class)

                                .putExtra("type", login_type)

                                .putExtra("phone", admin)

                                .putExtra("account",account)

                        );

                    }

                }

                break;



//            获取验证码
            case R.id.tv_register_code:

                true_account = et_admin.getText().toString().trim();

                get_code_net();

                break;


        }

    }

    private void register_net() {

        getRegisterUser.phone = et_admin.getText().toString().trim();

        getRegisterUser.loginType = String.valueOf(login_type);

        if(login_type == 1){

            getRegisterUser.weChat = account;

        }else if(login_type == 2){

            getRegisterUser.qq = account;

        }

        getRegisterUser.execute(this);

    }

    /***
     * 获取验证码
     */
    private void get_code_net() {

        new GetVerificationCode(et_admin.getText().toString().trim(), new AsyCallBack<GetVerificationCode.Info>() {

            @Override
            public void onSuccess(String toast, int type, GetVerificationCode.Info info) throws Exception {

                if (info.msg.equals("000")) {

                    if(login_type == 0 && info.flag.equals("0")){

                        UtilToast.show(context, "该手机号已被注册");

                    }else {

                        UtilToast.show(context, "验证码已经发送到您的手机中");

                        identifying_code = info.authCode;

                        account_flag = info.flag;

                        first_get_code();

                    }

                } else {

                    UtilToast.show(context, info.msg);

                }
            }
        }).execute(this);

    }

    private void first_get_code() {

        new CountDownTimer(60000, 1000) {// 两个参数，前一个指倒计时的总时间，后一个指多长时间倒数一下。

            @Override
            public void onTick(long millisUntilFinished) {

                tv_register_code.setText("重新获取(" + millisUntilFinished
                        / 1000 + ")");

                tv_register_code.setEnabled(false);
            }

            @Override
            public void onFinish() {

                tv_register_code.setText("重新获取验证码");

                tv_register_code.setEnabled(true);

            }
        }.start();

    }

    private void QQLogin(){

        Platform platform1 = ShareSDK.getPlatform(QQ.NAME);

        platform1.removeAccount(true);

        platform1.setPlatformActionListener(new PlatformActionListener() {
            // 回调：授权失败
            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                Log.e("****", arg2.toString());
                Message message = new Message();
                message.what = 1;
//                han.sendMessage(message);

            }
            // 回调：授权成功
            @Override
            public void onComplete(final Platform arg0,
                                   int arg1, final HashMap<String, Object> arg2) {
                Log.e("@@@", arg2.toString());
                runOnUiThread(new Runnable() {
                    public void run() {
                        Log.e("****", "onComplete");
                        Message message = new Message();
                        message.what = 2;
//                        han.sendMessage(message);
                        // 获取资料
//                                arg0.getDb().getUserName();// 获取用户名字
//                                arg0.getDb().getUserIcon(); // 获取用户头像
//                        openid= arg0.getDb().getUserId();
                        Log.e("openId",  arg0.getDb().getUserId());
//                                mUrl = mUrlStr1
//                                        + arg0.getDb().getToken()
//                                        + "&openid="
//                                        + arg0.getDb().getUserId();
//                                Webuse w = new Webuse();
//                                if (w.isNetworkAvailable(LoginActivity.this)) {
//                                    new LoginDataTask1().execute();
//                                } else {
//                                    Toast.makeText(LoginActivity.this, "当前没有可用网络！", Toast.LENGTH_LONG).show();
//                                }
                    }
                });

            }
            // 回调：授权取消
            @Override
            public void onCancel(Platform arg0, int arg1) {
                // TODO Auto-generated method stub
                Log.e("****", "onCancel");
//                han.sendEmptyMessage(3);
                Message message = new Message();
                message.what = 3;
//                han.sendMessage(message);
            }
        });
        platform1.showUser(null);



    }

}
